package me.ivps.android.weibo.dao.login;

import me.ivps.android.weibo.bean.UserBean;
import me.ivps.android.weibo.dao.URLHelper;
import me.ivps.android.weibo.support.debug.AppLogger;
import me.ivps.android.weibo.support.error.WeiboException;
import me.ivps.android.weibo.support.http.HttpMethod;
import me.ivps.android.weibo.support.http.HttpUtility;

import java.util.HashMap;
import java.util.Map;

import org.json.JSONException;
import org.json.JSONObject;

import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;

/**
 * OAuth 获取用户信息
 * 
 * User: Jiang Qi Date: 12-7-30
 */
public class OAuthDao {
    
    /**
     * 授权 access_token
     */
    private String access_token;
    
    public OAuthDao(String access_token) {
        this.access_token = access_token;
    }
    
    /**
     * 获取用户信息
     * 
     * @return
     * @throws WeiboException
     */
    public UserBean getOAuthUserInfo() throws WeiboException {
        String uidJson = getOAuthUserUIDJsonData();
        String uid = "";
        try {
            JSONObject jsonObject = new JSONObject(uidJson);
            uid = jsonObject.optString("uid");
        }
        catch (JSONException e) {
            AppLogger.e(e.getMessage());
        }
        
        Map<String, String> map = new HashMap<String, String>();
        map.put("uid", uid);
        map.put("access_token", access_token);
        
        String url = URLHelper.USER_SHOW;
        
        String result = HttpUtility.getInstance().executeNormalTask(
                HttpMethod.Get, url, map);
        
        Gson gson = new Gson();
        UserBean user = new UserBean();
        try {
            user = gson.fromJson(result, UserBean.class);
        }
        catch (JsonSyntaxException e) {
            AppLogger.e(result);
        }
        
        return user;
    }
    
    /**
     * 获取 Access_token 对应的用户数据信息
     * 
     * @return
     * @throws WeiboException
     */
    private String getOAuthUserUIDJsonData() throws WeiboException {
        String url = URLHelper.UID;
        Map<String, String> map = new HashMap<String, String>();
        map.put("access_token", access_token);
        return HttpUtility.getInstance().executeNormalTask(HttpMethod.Get, url,
                map);
    }
    
}
